package cn.com.backstage.controller;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.com.api.entity.*;
import cn.com.api.service.*;
import cn.com.backstage.controller.base.U_advertBaseController;
import cn.com.util.DateUtil;
import cn.com.util.JsonUtil;
import cn.com.util.Util;
import cn.com.util.Utils;

@Controller
@RequestMapping(Utils.SYS_BACKSTAGE + "/")
public class U_advertController extends U_advertBaseController {

	private static Logger logger = Logger.getLogger(U_advertController.class);

	@Autowired
	private ApiU_advertService apiU_advertService;
	@Autowired
	private ApiU_advert_positionService apiU_advert_positionService;
	@Autowired
	private ApiU_advert_resourceService apiU_advert_resourceService;
	@Autowired
	private ApiT_member_entrepreneurService apiT_member_entrepreneurService;

	/**
	 * 列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "advert-list")
	public ModelAndView advert_list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/u_advert_list.jsp");
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("nobonus", 1);
		String position_id = request.getParameter("position_id");
		map.put("position_id", position_id);

		List<Map<String, String>> u_adverts = apiU_advertService.findU_adverts_infos(map);
		mv.addObject("u_adverts", u_adverts);

		List<ApiU_advert_position> advert_positions = apiU_advert_positionService.findU_advert_positions();
		mv.addObject("advert_positions", advert_positions);
		//
		return mv;
	}

	/**
	 * 新增或者编辑
	 * 
	 * @return
	 */
	@RequestMapping(value = "advert-add")
	public void advert_add(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		String adv_name = request.getParameter("adv_name");
		String adv_desc = request.getParameter("adv_desc");
		String add_time = request.getParameter("add_time");
		String ent_id = request.getParameter("ent_id");
		String resource_type = request.getParameter("resource_type");

		// 地区信息 格式：江苏省/常州市/溧阳市
		String province = "";
		String city = "";
		String area = "";
		String regioninfo = request.getParameter("regioninfo");
		if (regioninfo != null && !"".equals(regioninfo.trim())) {
			String[] regions = regioninfo.split("/");
			province = regions[0];
			city = regions[1];
			area = regions[2];
		}

		String total_amount = request.getParameter("total_amount");
		String age_range = request.getParameter("age_range");
		String job_title = request.getParameter("job_title");

		String[] labels = request.getParameterValues("label");
		String interest_key = "";// 兴趣爱好
		if (labels != null && labels.length > 0) {
			interest_key = Util.join(":", labels);
		}

		String latitude = request.getParameter("latitude");
		String longitude = request.getParameter("longitude");
		String sort = request.getParameter("sort");

		String detail_url = request.getParameter("detail_url");
		String distance_range = request.getParameter("distance_range");
		String start_time = request.getParameter("start_time");
		String end_time = request.getParameter("end_time");
		String address = request.getParameter("address");
		String covers = request.getParameter("covers");// 图片或者视频的地址
		String position_id = request.getParameter("position_id");

		Map<String, Object> map = new HashMap<String, Object>();
		if (id == null || (id.trim()).equals("")) {// add
			ApiU_advert u_advert = new ApiU_advert();
			u_advert.setAdv_name(adv_name);
			u_advert.setAdv_desc(adv_desc);
			u_advert.setZan_count(0);
			u_advert.setPosition_id(Integer.valueOf(position_id));
			u_advert.setCity(city);
			u_advert.setTotal_amount(new BigDecimal(total_amount));
			u_advert.setEnt_id(ent_id.split("_")[0]);// 企业id
			u_advert.setAdd_uid(ent_id.split("_")[1]);// 发布人id
			u_advert.setAdv_name(adv_name);
			u_advert.setAdv_desc(adv_desc);
			u_advert.setAdd_time(DateUtil.nowTimeToString());
			u_advert.setResource_type(Integer.valueOf(resource_type));
			u_advert.setProvince(province);
			u_advert.setCity(city);
			u_advert.setArea(area);
			u_advert.setTotal_amount(new BigDecimal(total_amount));
			u_advert.setAge_range(age_range);
			u_advert.setJob_title(job_title);
			u_advert.setInterest_key(interest_key);
			ApiT_member_entrepreneur apiT_member_entrepreneur = apiT_member_entrepreneurService
					.findT_member_entrepreneurById(Integer.valueOf(ent_id.split("_")[0]));
			u_advert.setLogo(apiT_member_entrepreneur.getLogo_img());
			u_advert.setLatitude(latitude);
			u_advert.setLongitude(longitude);
			u_advert.setSort(Integer.valueOf(sort));
			u_advert.setDetail_url(detail_url);
			u_advert.setDistance_range(Long.valueOf(distance_range));
			u_advert.setStart_time(start_time);
			u_advert.setEnd_time(end_time);
			u_advert.setStatus(1);
			u_advert.setIs_pay(1);
			u_advert.setAddress(address);
			u_advert.setCovers(covers);
			apiU_advertService.U_advertInsertion(u_advert);
			if ("1".equals(resource_type)) {// 视频广告 将七牛的视频地址存到资料表
				ApiU_advert_resource u_advert_resource = new ApiU_advert_resource();
				u_advert_resource.setAdvert_id(u_advert.getId() + "");
				u_advert_resource.setResource_url(covers);
				apiU_advert_resourceService.insertU_advert_resource(u_advert_resource);
			}
		} else {// edit
			ApiU_advert u_advert = apiU_advertService.findU_advertById(Integer.valueOf(id));
			u_advert.setAdv_name(adv_name);
			u_advert.setAdv_desc(adv_desc);
			u_advert.setZan_count(0);
			u_advert.setAdd_time(add_time);
			u_advert.setResource_type(Integer.valueOf(resource_type));
			u_advert.setProvince(province);
			u_advert.setCity(city);
			u_advert.setTotal_amount(new BigDecimal(total_amount));
			u_advert.setAge_range(age_range);
			u_advert.setJob_title(job_title);
			u_advert.setInterest_key(interest_key);
			u_advert.setLatitude(latitude);
			u_advert.setLongitude(longitude);
			u_advert.setShow_times(0);
			u_advert.setEnt_id(ent_id.split("_")[0]);// 企业id
			u_advert.setAdd_uid(ent_id.split("_")[1]);// 发布人id
			u_advert.setSort(Integer.valueOf(sort));
			u_advert.setArea(area);
			u_advert.setDetail_url(detail_url);
			u_advert.setDistance_range(Long.valueOf(distance_range));
			u_advert.setStart_time(start_time);
			u_advert.setEnd_time(end_time);
			u_advert.setAddress(address);
			u_advert.setCovers(covers);
			apiU_advertService.updateU_advert(u_advert);
			if ("1".equals(resource_type)) {// 视频广告 将七牛的视频地址存到资料表
				apiU_advert_resourceService.deleteAdvertResource(u_advert.getId());
				ApiU_advert_resource u_advert_resource = new ApiU_advert_resource();
				u_advert_resource.setAdvert_id(u_advert.getId() + "");
				u_advert_resource.setResource_url(covers);
				apiU_advert_resourceService.insertU_advert_resource(u_advert_resource);
			}
		}
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "添加成功！");
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 跳转到广告审核界面
	 * 
	 * @return
	 */
	@RequestMapping(value = "tocheckadvert")
	public ModelAndView tocheckadvert(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String advertid = request.getParameter("advertid");
		ModelAndView mv = new ModelAndView("forward:/backstage/u_advert_check.jsp");
		mv.addObject("advertid", advertid);
		return mv;
	}

	/**
	 * 审核广告
	 * 
	 * @return
	 */
	@RequestMapping(value = "updateadvertstatus")
	public void updateadvertstatus(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String advertid = request.getParameter("advertid");
			String reason = request.getParameter("reason");
			String status = request.getParameter("status");
			ApiU_advert advert = apiU_advertService.findU_advertById(Integer.valueOf(advertid));
			if ("1".equals(status)) {// 同意时
				if (advert.getPosition_id() == 3) {// 红包广告时，审核成功后计算开始时间和结束时间
					Integer sign_term = advert.getSign_term();// 投放天数
					Date now = new Date();
					String start_time = DateUtil.dateToString(now, "yyyy-MM-dd HH:mm:ss");
					String end_time = DateUtil.dateToString(DateUtil.getDateAfter(new Date(), sign_term),
							"yyyy-MM-dd HH:mm:ss");
					advert.setStart_time(start_time);
					advert.setEnd_time(end_time);
				}
			}
			advert.setStatus(Integer.valueOf(status));
			if (reason != null && !"".equals(reason)) {
				advert.setExt1(reason);
			}
			apiU_advertService.updateU_advert(advert);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	public static void main(String args[]) {
		// 便利实体类的属性名与值
		try {
			ApiGoods apiGoods = new ApiGoods();
			Field[] fields = ApiGoods.class.getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);
				System.err.println("key:" + field.getName() + ",value:" + field.get(apiGoods));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
